package edu.gatech.oad.yuno;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Provides methods to get a list of Todo's based on some parameters.
 * @author michael
 *
 */
public class SearchProvider {
	public static List<Todo> filter(long userId, int priority, long locationId,
			long categoryId, Date startDate, Date endDate) {
		List<Todo> list = new ArrayList<Todo>();
		TodoListOpenHelper helper = new TodoListOpenHelper(YUNoDosApplication.getAppContext());
		SQLiteDatabase db = helper.getReadableDatabase();
		String cols[] = {"id"};
		
		StringBuilder where = new StringBuilder("user_id="+Long.toString(userId));
		
		if (priority > 0) {
			where.append(" AND priority >= "+Integer.toString(priority));
		}
		if (locationId != 0) {
			where.append(" AND location_id="+Long.toString(locationId));
		}
		if (categoryId != 0) {
			where.append(" AND category_id="+Long.toString(categoryId));
		}
		if (startDate != null) {
			where.append(" AND due_date >= "+Long.toString(startDate.getTime()));
		}
		if (endDate != null) {
			where.append(" AND due_date <= "+Long.toString(endDate.getTime()+24*60*60));
		}
		
		Cursor c = db.query("todos", cols, where.toString(), null, null, null, null, null);
		if (c == null || c.getCount() < 1) {
			db.close();
			return list;
		}
		c.moveToFirst();
		list.add(new Todo(c.getLong(c.getColumnIndex("id"))));
		while (!c.isLast()) {
			c.moveToNext();
			list.add(new Todo(c.getLong(c.getColumnIndex("id"))));
		}
		Collections.sort(list);
		db.close();
		return list;
	}
	
	public static List<Todo> filter(User user, int priority, Location location,
			Category category, Date startDate, Date endDate) {
		long userId = 0;
		long locationId = 0;
		long categoryId = 0;
		if (user != null) userId = user.getId();
		if (location != null) locationId = location.getId();
		if (category != null) categoryId = category.getId();
		return filter(userId, priority, locationId, categoryId, startDate, endDate);
	}
	
	public static List<Todo> excludeCompleted(List<Todo> list){
		List<Todo> outlist = new ArrayList<Todo>();
		for (Todo todo: list){
			if (!todo.isCompleted()){
				outlist.add(todo);
			}
		}
		return outlist;
	}
}

